package toy.keli.edic.ui.main.extend

import android.os.Handler
import android.widget.Toast
import androidx.collection.arrayMapOf
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import toy.keli.edic.util.ActivityRun.Companion.context


fun bgRun(run:()->Unit)  {
    CoroutineScope(Dispatchers.IO).launch {
                run()
    }
}
fun MainRun(timeMs:Long,run:()->Unit)  {
    Handler().postDelayed({
        try{
            run()
        }catch (e:Exception){
            e.printStackTrace()
        }
    },timeMs)
}
fun MainRun(run:()->Unit)  {
    runBlocking{
        withContext(Dispatchers.Main) {
            run()
        }
    }
}

fun MainMsg(msg:String){
    MainRun {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
    }
}

/**
 * 串行运行 延迟时间内连续执行只会最后一次延迟后执行一次
 */
val stringRunMap= arrayMapOf<String,ArrayList<Long>>()
fun stringRun(timeMs:Long,run:()->Unit){
    val rid = run.javaClass.name
    val queue: ArrayList<Long> = if(stringRunMap.containsKey(rid))  stringRunMap.get(rid)!! else arrayListOf<Long>()
    queue.add(System.currentTimeMillis())
    stringRunMap.set(rid,queue)
    CoroutineScope(Dispatchers.IO).launch {
        delay(timeMs)
        val queue = stringRunMap.get(rid)!!
        queue.removeAt(0)
        if(queue.size==0) {
            run()
        }
    }
}

/**
 * 只运行一次
 */
val oneRunMap= arrayMapOf<String,Boolean>()
fun oneRun(run:()->Unit){
    val rid = run.javaClass.name
    if(oneRunMap[rid]==null){
        oneRunMap[rid] = true
        run()
    }
}